package com.itheima.record.service.impl;


import com.itheima.record.pojo.FieldRecord;
import com.itheima.record.mapper.FieldRecordMapper;
import com.itheima.record.service.FieldRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author
 * @since 2020-10-11
 */
@Service
public class FieldRecordServiceImpl implements FieldRecordService {


    @Autowired
    private FieldRecordMapper fieldRecordMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    提交业务处理:
    1.接受参数后,不存入数据库,保存到redis当中
    2.对于表格我对应实体类数据,用redis hash进行存储
     */
    @Override
    public void add(FieldRecord fieldRecord) {

        redisTemplate.opsForHash().put("RECORD"+fieldRecord.getDate(),"1",fieldRecord);

        List<FieldRecord> list = redisTemplate.opsForHash().values("RECORD" + fieldRecord.getDate());
        for (FieldRecord f : list) {
            System.out.println(f);
        }
    }

    /*
    修改业务:
    1.进行更改后,我先删除redis的数据,然后再添加
     */
    @Override
    public void update(String date,FieldRecord fieldRecord) {
        String value = "RECORD"+date;
        Map map = redisTemplate.opsForHash().entries(value);
        System.out.println(map);
        System.out.println(date);
        redisTemplate.opsForHash().delete("RECORD"+date,"1");


        redisTemplate.opsForHash().put("RECORD"+fieldRecord.getDate(),"1",fieldRecord);

        List<FieldRecord> list = redisTemplate.opsForHash().values("RECORD" + fieldRecord.getDate());
        for (FieldRecord fieldRecord1 : list) {
            System.out.println(fieldRecord1);
        }

    }

    /*
    提交业务:
    1.根据日期,为什么不用id呢,用户提交的时候没有id,插入数据库会有id,我们用日期作为识别标识
    2.用redis取出来后,用户点击提交,那么我们直接存储到数据库中.
     */
    @Override
    public void commit(String date) {
        List<FieldRecord> list = redisTemplate.opsForHash().values("RECORD" +date);
        for (FieldRecord f : list) {
            fieldRecordMapper.insert(f);
        }
        redisTemplate.opsForHash().delete("RECORD"+date,"1");
    }

        /*
    查看日报:
    1.我们提交日报后,就可以展示当天的日报了
     */

    @Override
    public FieldRecord find(String date) {

        //自定义类
        Example example=new Example(FieldRecord.class);
        //获取条件构建期
        Example.Criteria criteria = example.createCriteria();

        if (date!=null){
            //根据日期查询
            criteria.andEqualTo("date",date);
        }
        //执行自定义查询
        List<FieldRecord> fieldRecords = fieldRecordMapper.selectByExample(example);
        for (FieldRecord fieldRecord : fieldRecords) {
            return fieldRecord;
        }
        return null;
    }
}
